Mapping Over Data
Alright, so let's suppose that the data for our CRM is held in an array, like this:
Code Playground
We want to create a <ContactCard>
element for each of the contacts in the data
array, passing in their name/job/email.
In other frameworks like Vue and Angular, special syntax is provided for doing iteration. In React, however, we rely purely on JavaScript. There is no “React syntax” for doing this sort of iteration.
If you're feeling adventurous, spend a few minutes and see if you can figure out how to solve this problem! It's OK if you're not sure. Experiment, and see what happens! This is the best way to start building an intuition.
I'll share my approach below.
My approach
Video Summary
- Unlike in other template languages, there is no directive like
v-for
or#each
to help with iteration. - There is one thing React does provide for us: we can pass an array, and React will unpack and render each item for us. For example, we can render
{['hello', 'world']}
and we'll see the content “helloworld” included in the DOM. - So, the solution is to create an array of React elements, and then to pass that array to React in the JSX.
- There are lots of ways we can create an array of elements: we could use a
for
loop, for example. But by far the most common method is to use the.map
method. - We can call
data.map
and render a<ContactCard>
element for each one. Then, we can create an expression slot inside the<ul>
to receive that array.- We do get a warning in the developer console about missing keys. We'll address this warning in the next lesson.
- This is the beautiful thing about React. We don't have to learn a “magical” new syntax, we can use the JavaScript we know and love! For example,
slice
lets us render a subset of the array.
The JavaScript Primer bonus module has some relevant lessons for this approach:
- Array Iteration Methods 👀 (specifically the
map
method)
JSX inside JS inside JSX
When iterating in React, it's not uncommon to wind up with structures like this:
<ul> {items.map(item => ( <li>{item}</li> ))}</ul>
On the second line, we use curly brackets to add some "vanilla JS" to our JSX. But then we're using JSX inside those curly brackets! Some developers are caught off guard by the fact that this is "legal".
The JSX compiler is able to resolve "nested" JSX calls without issue. The end result is something like this:
React.createElement( 'ul', {}, items.map(item => ( React.createElement( 'li', {}, item ) )));